package com.woniuxy.java102vuecli.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.java102vuecli.entity.Employee;
import com.woniuxy.java102vuecli.entity.PageBean;
import com.woniuxy.java102vuecli.exception.EmailExistsException;
import com.woniuxy.java102vuecli.exception.EnameNotExistsException;
import com.woniuxy.java102vuecli.exception.PasswordIncorrectException;
import com.woniuxy.java102vuecli.mapper.EmployeeMapper;
import com.woniuxy.java102vuecli.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * @Author author
 * @Create 2023-09-14 11:42
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public PageBean<Employee> getEmployees(int pageIndex, int pageSize, Employee employee) {
        //分页插件底层就是拦截器，AOP：执行查询之前调用织入：select count(*)   select *  limit ?，?
        PageHelper.startPage(pageIndex, pageSize);
        List<Employee> employess = employeeMapper.getEmployees(employee);
        PageInfo<Employee> pageInfo=new PageInfo<>(employess);
        PageBean<Employee> pageBean=new PageBean<>(pageIndex,pageSize, (int) pageInfo.getTotal(),
                pageInfo.getPages(),employess);
        return pageBean;
    }

    @Override
    public Boolean emailExists(String email) {
        return employeeMapper.getEmployeeByEmail(email)!=null;
    }

    @Override
    public void addEmployee(Employee employee) {
        //执行添加业务规则判断:用户名，邮箱，手机号，如果被使用
        if(emailExists(employee.getEmail())){
            //抛异常
            throw new EmailExistsException("邮箱被使用");
        }
        //if(用户名)
        //if(手机号)
        //表中添加列salt,随机生成，“原始密码”+salt加密，存储
        employee.setPassword(DigestUtils.md5DigestAsHex("aaa".getBytes()));
        employeeMapper.insertEmployee(employee);
    }

    @Override
    public Employee login(String ename, String password) {
        //外网系统：登录失败，用户名或者密码错误
        //内部系统：用户名不存在，密码错误
        Employee employee = employeeMapper.getEmployeeByEname(ename);
        if(employee==null){
            throw new EnameNotExistsException("用户名不存在");
        }
        if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(employee.getPassword())){
            throw new PasswordIncorrectException("密码错误");
        }
        //返回用户对象
        return employee;
    }
}
